/* eslint-disable no-alert */
import axios from 'axios'
// import { get, set } from 'js-cookie'
import { get } from 'js-cookie'
import { logout } from '@/utils'
import { stringify } from 'qs'
// import authAPI from '@/interface/index'
import { Message } from 'element-ui'

// 检查并刷新token
// function checkToken() {
//   const token = get('token')
//   authAPI.refreshToken({ token }).then((result) => {
//     if (result.success) {
//       set('token', result.accessToken)
//       Message({ type: 'info', message: '权限已更新，请重新进行操作' })
//     } else {
//       const refreshToken = get('refreshToken')
//       set('token', refreshToken)
//       Message({ type: 'error', message: '权限已失效，请重新登录', duration: 1000 })
//       // logout.call(window.$vm)
//     }
//   }).catch((err) => {
//     console.log(err)
//     // 重新登录
//     Message({ type: 'error', message: err, duration: 1000 })
//     // logout.call(window.$vm)
//   })
// }
axios.defaults.timeout = 30000
axios.defaults.retry = 3
axios.defaults.retryDelay = 1000

// 定义全局变量clearRequest，在route.js中要用到
const clearRequest = {
  source: {
    token: null,
    cancel: null
  }
}
const CancelToken = axios.CancelToken
const source = CancelToken.source()
// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    config.cancelToken = clearRequest.source.token
    return config
  },
  error => Promise.reject(error)
)
// 添加响应拦截器
axios.interceptors.response.use(response =>
  response
,
(error) => {
  console.log(error.response)
  if (+error.response.status === 401) {
    // checkToken()
    Message({
      type: 'waring',
      message: '权限过期，请重新登录'
    })
    logout()
  }
  return Promise.reject(error)
}
)
export function api(data) {
  const { url, method, isStringify } = data
  let params = data.params
  const token = get('token')
  const newHeader = {
    'Content-Type': 'application/json;charset=UTF-8',
    Authorization: `Bearer ${token}`
  }
  // 需要序列化
  if (isStringify) {
    newHeader['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    if (method !== 'get') {
      params = stringify(params, { arrayFormat: 'repeat' })
    }
  }
  let backHost = 'http://127.0.0.1:11027'
  backHost = `${backHost}/mooc/v1`
  const newApi = `${backHost}${url}`
  return axios(
    { method,
      url: newApi,
      cancelToken: source.token,
      timeout: 30000,
      data: params,
      params: method.toLocaleLowerCase() === 'get' ? params : {},
      headers: newHeader,
      paramsSerializer(p) {
        return stringify(p, { arrayFormat: 'repeat' })
      }
    })
    .then((res) => {
      if (+res?.code === 401) {
        // checkToken()
        return Promise.resolve(undefined)
      }
      return Promise.resolve(res.data)
    })
    .catch((e) => {
      console.log(e.message)
    })
}
export { clearRequest }
